package com.itheima.controller;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import com.itheima.common.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 实现文件的上传下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /*@GetMapping("/download")
    public ResponseEntity<?> getImagesByName(@RequestParam String name) {
        // 打印文件名，进行调试
        System.out.println("Requesting file: " + name);

        // 图片文件存储路径
        String filePath = "src/main/resources/backend/common/download";
        File file = new File(filePath + File.separator + name);

        // 检查文件是否存在
        if (!file.exists()) {
            System.err.println("File not found: " + file.getAbsolutePath());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File not found");
        }

        // 构建文件资源
        FileSystemResource fileSystemResource = new FileSystemResource(file);

        // 构建响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + name);
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        // 返回文件流给前端
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(fileSystemResource);
    }*/

    /**
     * 文件的上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        //原始文件名
      String originalFilename =  file.getOriginalFilename();
      String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

      //使用UUID随机名字
        String filename = UUID.randomUUID().toString()+suffix;

        File dir = new File(basePath);
      //创建一个目录文件
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(filename);
    }

    @GetMapping("download")
    public void download(String name,HttpServletResponse response){

        try{//输入流的读文件的名字，输出流写回浏览器
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));

            //往浏览器写
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");
            int len = 0;
            byte[] buffer = new byte[1024];
            while((len =fileInputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,len);
                outputStream.flush();
            }

            //关闭资源
            fileInputStream.close();
            outputStream.close();
        }catch (IOException e){
            throw new RuntimeException(e);
        }

    }
}
